package tags

import (
	"encoding/json"
	"errors"
	"time"

	"github.com/ipfs/ipfs-cluster/config"
	"github.com/kelseyhightower/envconfig"
)

const configKey = "tags"
const envConfigKey = "cluster_tags"

// Default values for tags Config
const (
	DefaultMetricTTL = 30 * time.Second
)

// Default values for tags config
var (
	DefaultTags = map[string]string{
		"group": "default",
	}
)

// Config is used to initialize an Informer and customize
// the type and parameters of the metric it produces.
type Config struct {
	config.Saver

	MetricTTL time.Duration
	Tags      map[string]string
}

type jsonConfig struct {
	MetricTTL string            `json:"metric_ttl"`
	Tags      map[string]string `json:"tags"`
}

// ConfigKey returns a human-friendly identifier for this type of Metric.
func (cfg *Config) ConfigKey() string {
	return configKey
}

// Default initializes this Config with sensible values.
func (cfg *Config) Default() error {
	cfg.MetricTTL = DefaultMetricTTL
	cfg.Tags = DefaultTags
	return nil
}

// ApplyEnvVars fills in any Config fields found
// as environment variables.
func (cfg *Config) ApplyEnvVars() error {
	jcfg := cfg.toJSONConfig()

	err := envconfig.Process(envConfigKey, jcfg)
	if err != nil {
		return err
	}

	return cfg.applyJSONConfig(jcfg)
}

// Validate checks that the fields of this Config have working values,
// at least in appearance.
func (cfg *Config) Validate() error {
	if cfg.MetricTTL <= 0 {
		return errors.New("tags.metric_ttl is invalid")
	}

	return nil
}

// LoadJSON reads the fields of this Config from a JSON byteslice as
// generated by ToJSON.
func (cfg *Config) LoadJSON(raw []byte) error {
	jcfg := &jsonConfig{}
	err := json.Unmarshal(raw, jcfg)
	if err != nil {
		logger.Error("Error unmarshaling disk informer config")
		return err
	}

	cfg.Default()

	return cfg.applyJSONConfig(jcfg)
}

func (cfg *Config) applyJSONConfig(jcfg *jsonConfig) error {
	err := config.ParseDurations(
		cfg.ConfigKey(),
		&config.DurationOpt{Duration: jcfg.MetricTTL, Dst: &cfg.MetricTTL, Name: "metric_ttl"},
	)
	if err != nil {
		return err
	}

	cfg.Tags = jcfg.Tags

	return cfg.Validate()
}

// ToJSON generates a JSON-formatted human-friendly representation of this
// Config.
func (cfg *Config) ToJSON() (raw []byte, err error) {
	jcfg := cfg.toJSONConfig()

	raw, err = config.DefaultJSONMarshal(jcfg)
	return
}

func (cfg *Config) toJSONConfig() *jsonConfig {
	return &jsonConfig{
		MetricTTL: cfg.MetricTTL.String(),
		Tags:      cfg.Tags,
	}
}

// ToDisplayJSON returns JSON config as a string.
func (cfg *Config) ToDisplayJSON() ([]byte, error) {
	return config.DisplayJSON(cfg.toJSONConfig())
}
